package com.qf.admin.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import com.alibaba.excel.EasyExcel;
import com.qf.admin.entity.Goods;
import com.qf.admin.entity.Item;
import com.qf.admin.listener.ExcelGoodsListener;
import com.qf.admin.model.Results;
import com.qf.admin.model.TableData;
import com.qf.admin.pojo.AddGoods;
import com.qf.admin.pojo.EditGoods;
import com.qf.admin.pojo.QueryGoods;
import com.qf.admin.service.IGoodsService;
import com.qf.admin.vo.ExcelGoods;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/goods")
@CrossOrigin(origins = "*")
public class GoodsController {

    @Value("${fileTempDir}")
    private String fileTampDir;


    private IGoodsService goodsService;

    public GoodsController(IGoodsService goodsServiceImpl) {
        this.goodsService = goodsServiceImpl;
    }

    //获取分页的商品数据
    @GetMapping
    public TableData<Goods> getGoodsData(QueryGoods queryGoods,
                                         @RequestParam(defaultValue = "0") Integer offset,
                                         @RequestParam(defaultValue = "10") Integer limit) {

        System.out.println(queryGoods);

        TableData<Goods> goodsData = goodsService.getGoodsData(queryGoods,offset, limit);

        return goodsData;

    }

    //根据商品id删除商品，也就是修改商品状态
    @PutMapping("/{id}")
    public Results deleteGoodsById(@PathVariable("id") Integer id) {

        Results results = new Results();
        try {
            goodsService.deleteGoodsById(id);
            results.setCode(1);
            results.setMsg("success");
        } catch (Exception e) {
            e.printStackTrace();
            results.setCode(-1);
            results.setMsg("fail");
        }

        return results;
    }

    /**
     * 编辑商品
     */

    //根据id查询商品数据用于回显
    @GetMapping("/{id}")
    public EditGoods editGoodsById(@PathVariable("id") Integer id) {

        EditGoods editGoods = goodsService.editGoodsById(id);

        return editGoods;
    }

    //保存编辑后的商品数据
    @PostMapping
    public Results editGoodsAndSave(EditGoods editGoods) {
        Results results = new Results();
        try {
            goodsService.editGoodsAndSave(editGoods);

            results.setCode(1);
            results.setMsg("success");
        } catch (Exception e) {
            e.printStackTrace();
            results.setCode(-1);
            results.setMsg("fail");
        }
        return results;
    }


    /**
     * 添加商品
     */

    //展示商品的种类
    @GetMapping("item")
    public List<Item> showAllItems() {

        List<Item> allItem = goodsService.getAllItem();

        return allItem;

    }

    //添加商品回显图片
    @PostMapping("/update")
    public Map<String, String> updateImage(MultipartFile displayImage, String itemAlias) {

        Map<String, String> map = null;
        try {
            map = goodsService.updateImage(displayImage, itemAlias);
            map.put("yes","success");
        } catch (IOException e) {
            e.printStackTrace();
            map.put("no","fail");
        }
        return map;
    }

    //添加商品
    @PostMapping("/add")
    public Results addGoods(AddGoods addGoods){
        Results results = new Results();
        try {
            goodsService.addGoodsMethod(addGoods);
            results.setCode(1);
            results.setMsg("success");
        }catch (Exception e){
            e.printStackTrace();
            results.setCode(-1);
            results.setMsg("fail");
        }

        return results;

    }

    //导入excel文件
    @PostMapping("/import")
    public Results importExcel(MultipartFile goodsExcel) {

        Results results = new Results();

        try {
            EasyExcel.read(goodsExcel.getInputStream(), ExcelGoods.class, new ExcelGoodsListener(goodsService)).sheet().doRead();
            results.setCode(1);
            results.setMsg("success");
        } catch (IOException e) {
            e.printStackTrace();
            results.setCode(-1);
            results.setMsg("fail");
        }

        return results;
    }

    //导出excel文件
    @GetMapping("/export")
    public void exportExcel(QueryGoods queryGoods,HttpServletResponse response) {

        System.out.println("==========");

        System.out.println(queryGoods);

        //获取所有商品的数据
        List<Goods> allGoods = goodsService.getAllGoods(queryGoods);

        //创建新的excel文件名
        String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + ".xlsx";

        //完整的路径
        String fullPath = fileTampDir + fileName;

        //创建封装数据的集合
        List<ExcelGoods> excelGoodsList = new ArrayList<>(allGoods.size());

        //将数据封装到excelGoods结合中
        for (Goods good : allGoods) {
            ExcelGoods excelGoods = new ExcelGoods(good.getTid(),good.getType(), good.getGid(), good.getTitle(), good.getPrice()
                    , good.getCreateTime(), good.getUpdateTime(), good.getStatus(), good.getStock());

            //将对象封装到相应的集合当中
            excelGoodsList.add(excelGoods);
        }

        //清除allGoods集合
        allGoods = null;

        //将excel写入临时目录
        EasyExcel.write(new File(fullPath), ExcelGoods.class).sheet().doWrite(excelGoodsList);

        //清除excelGoodsList结合清除
        excelGoodsList = null;

        //下载excel文件到本地， 文件下载的头信息设置
        response.setHeader("content-disposition", "attachment;filename=" + fileName);

        try {
            IoUtil.copy(new FileInputStream(fullPath), response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
